package com.lijian.community.service.impl;

import com.github.pagehelper.PageHelper;
import com.lijian.community.dto.PaginationDTO;
import com.lijian.community.dto.QuestionDTO;
import com.lijian.community.dto.QuestionQueryDTO;
import com.lijian.community.exception.CustomizeErrorCode;
import com.lijian.community.exception.CustomizeException;
import com.lijian.community.mapper.QuestionMapper;
import com.lijian.community.mapper.UserMapper;
import com.lijian.community.model.Question;
import com.lijian.community.model.User;
import com.lijian.community.service.QuestionService;
import com.lijian.community.utils.PagedResult;
import com.lijian.community.utils.PagedResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class QuestionServiceImpl implements QuestionService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private QuestionMapper questionMapper;

    @Override
    public PaginationDTO findAll(String search, Integer page, Integer size) {

        if(StringUtils.isNotBlank(search)){
            String[] tags = StringUtils.split(search, " ");
            search =  Arrays.stream(tags).collect(Collectors.joining("|"));
        }
        /**
         * 分页
         */
        QuestionQueryDTO questionQueryDTO = new QuestionQueryDTO();
        questionQueryDTO.setSearch(search);
        Integer totalCount = questionMapper.countBySearch(questionQueryDTO);

        PageHelper.startPage(page, size);
        List<Question> questionList = questionMapper.findBySearch(questionQueryDTO);
        PagedResultUtil<Question> resultUtil = new PagedResultUtil();
        PagedResult pagedResult = resultUtil.setPagedResult(questionList);

        PaginationDTO paginationDTO = new PaginationDTO();
        //Long totalCountL = pagedResult.getRecords();
        //totalCountL转成int型
        //Integer totalCount = Math.toIntExact(totalCountL);

        paginationDTO.setPagination(totalCount, page, size);

        List<QuestionDTO> questionDTOList = new ArrayList<>();
        for (Question question : questionList) {
            User user = userMapper.findById(question.getCreator());
            //System.out.println(user.toString());
            QuestionDTO questionDTO = new QuestionDTO();
            //拷贝对象
            BeanUtils.copyProperties(question, questionDTO);
            questionDTO.setUser(user);

            questionDTOList.add(questionDTO);
        }
        paginationDTO.setData(questionDTOList);

        return paginationDTO;
    }

    @Override
    public PaginationDTO findAll(Integer userId, Integer page, Integer size) {
        /**
         * 分页
         */
        PageHelper.startPage(page, size);
        List<Question> questionList = questionMapper.findAllByUserId(userId);
        PagedResultUtil<Question> resultUtil = new PagedResultUtil();
        PagedResult pagedResult = resultUtil.setPagedResult(questionList);

        PaginationDTO paginationDTO = new PaginationDTO();
        Integer totalCount = questionMapper.countByUserId(userId);

        paginationDTO.setPagination(totalCount, page, size);

        List<QuestionDTO> questionDTOList = new ArrayList<>();
        for (Question question : questionList) {
            User user = userMapper.findById(question.getCreator());
            //System.out.println(user.toString());
            QuestionDTO questionDTO = new QuestionDTO();
            //拷贝对象
            BeanUtils.copyProperties(question, questionDTO);
            questionDTO.setUser(user);

            questionDTOList.add(questionDTO);
        }
        paginationDTO.setData(questionDTOList);

        return paginationDTO;
    }

    @Override
    public QuestionDTO findById(Integer id) {
       Question question =  questionMapper.findById(id);
       if(question == null){
           throw new CustomizeException(CustomizeErrorCode.QUESTION_NOT_FOUND);
       }
        QuestionDTO questionDTO = new QuestionDTO();
        BeanUtils.copyProperties(question, questionDTO);
        User user = userMapper.findById(question.getCreator());
        questionDTO.setUser(user);
        return questionDTO;
    }

    @Override
    public void createOrUpdateQuestion(Question question) {
        if(question.getId() == null){
            //创建问题
            question.setCreateTime(new Date());
            question.setUpdateTime(new Date());
            questionMapper.createQuestion(question);
        } else {
            //更新
            question.setUpdateTime(new Date());
            int result = questionMapper.updateQuestion(question);
            if(result != 1){
                throw new CustomizeException(CustomizeErrorCode.QUESTION_NOT_FOUND);
            }
        }

    }

    /**
     * 根据id更新阅读数
     * @param id
     */
    @Override
    public void incView(Integer id) {
        //更新阅读数
        questionMapper.updateView(id);

    }

    @Override
    public List<QuestionDTO> findRelated(QuestionDTO queryDTO) {
        if(StringUtils.isBlank(queryDTO.getTag())){
            return new ArrayList<>();
        }
        String[] tags = StringUtils.split(queryDTO.getTag(), ",");
        String regexTag = Arrays.stream(tags).collect(Collectors.joining("|"));
        Question question = new Question();
        question.setId(queryDTO.getId());
        question.setTag(regexTag);
        List<Question> questionList = questionMapper.findRelated(question);
        List<QuestionDTO> questionDTOList = questionList.stream().map(q -> {
            QuestionDTO questionDTO = new QuestionDTO();
            BeanUtils.copyProperties(q, questionDTO);
            return questionDTO;
        }).collect(Collectors.toList());
        return questionDTOList;
    }
}
